HackerRank Lily's Homework
提出
code: python
import math
import os
import random
import re
import sys
#
# Complete the 'lilysHomework' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY arr as parameter.
#
def lilysHomework(arr):
# Write your code here
# change = True
# ans = 0
# for i in range(len(arr)):
# if not change:
# break
# change = False
# for j in range(len(arr) - i - 1):
# ans += 1
# change = True
# return ans // 2
if __name__ == '__main__':
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
result = lilysHomework(arr)
fptr.write(str(result) + '\n')
fptr.close()
解答
code: python
import math
import os
import random
import re
import sys
#
# Complete the 'lilysHomework' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY arr as parameter.
#
def lilysHomework(arr):
# Write your code here
# create function to find no. of swaps
def no_of_swaps(arr):
indexmap = {}
for i in range(len(arr)):
# print(indexmap)
# {2: 0, 5: 1, 3: 2, 1: 3}
# sort the array
sorted_arr = sorted(arr)
result = 0
for i in range(len(arr)):
if arri != sorted_arri: # 2 != 1 result += 1
# swap element index
swap_index = indexmap[sorted_arri] # 3 # update swapping index
indexmap[arri] = swap_index # swap operation
return result
normal_order = no_of_swaps(arr::) reverse_order = no_of_swaps(arr::-1) return min(normal_order, reverse_order)
if __name__ == '__main__':
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
result = lilysHomework(arr)
fptr.write(str(result) + '\n')
fptr.close()
メモ
https://www.youtube.com/watch?v=eeoEqIKhYLI
提出
code: python
import math
import os
import random
import re
import sys
#
# Complete the 'lilysHomework' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY arr as parameter.
#
# 3 4 2 5 1
# 5 4 2 3 1
# 5 4 3 2 1
def lilysHomework(arr):
# Write your code here
ans = bubble_sort(arr)
return ans
if __name__ == '__main__':
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
result = lilysHomework(arr)
fptr.write(str(result) + '\n')
fptr.close()